
package hk.ces.oxfam.patch.transaction;

import hk.ces.oxfam.patch.TransactionPatch;
import hk.ces.oxfam.patch.TransactionStrategy;
import hk.ces.oxfam.patch.TransactionStrategyType;
import hk.ces.oxfam.patch.sql.ExcuteUtil;
import hk.ces.oxfam.patch.sql.PreparedSQL;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.Logger;

/**
 *
 * @author ReutyCheng
 */
@TransactionStrategy(TransactionStrategyType.ROLLBACK)
public class PersonInfoTypeToWalkerPatch implements TransactionPatch
{
  private static final String WALKER = "WALKER";
  
  public void run(Connection connection) throws SQLException
  {
    int walkerUpdateCount = 0;
    while (true)
    {
      int walkerUpdatedResult = this.updateRestPersonInfoToWalker(connection);
      Logger.getLogger(this.getClass()).debug("Update Walker[count=" + walkerUpdatedResult + "]");

      if (walkerUpdatedResult == 0)
      {
        break;
      }
      else
      {
        walkerUpdateCount += walkerUpdatedResult;
      }
    }
    Logger.getLogger(this.getClass()).debug("Totally update Walker[count=" + walkerUpdateCount + "]");
  }

  private int updateRestPersonInfoToWalker(Connection connection) throws SQLException
  {
    String sql = "update personinfo set personinfotype = ? where id in (select id from personinfo where personinfotype is null or personinfotype = '' fetch first 10000 rows only)";
    Object[] objects = new Object[] {
      WALKER
    };

    int result = ExcuteUtil.excute(connection, new PreparedSQL(sql, objects));
    Logger.getLogger(this.getClass()).debug("Patch other Person with PersonInfoType is [WALKER]");
    return result;
  }
}
